import { makeAutoObservable, toJS } from 'mobx';
import * as api from './api';
import moment from 'moment';

export default class OrderReportStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['salesDate;desc'],
      size: 10,
    },
  };
  total = 0
  _tabKey = 'ticket';
  _summaryTypes = [];
  tableData = [];
  loading = false;
  loadingTotal = false;
  summaryData = {};
  companyOptions = [];
  driverOptions = [];

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * @func
   * @desc
   * @param {}
   * @return {}
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined));
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    const tabKey = toJS(this._tabKey);
    try {
      this.total = yield api.count({ search }, tabKey);
      this.tableData = yield api.search({ search, pg }, tabKey);
    } finally {
      this.loading = false;
    }
  }

  * export(fileName) {
    const { search } = toJS(this._args);
    const type = toJS(this._tabKey);
    this.loading = true;
    try {
      yield api.exportTable({ search }, type).then((res) => {
        const blob = new Blob(
          res.map((buf) => Uint8Array.from(buf.data).buffer),
          {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          },
        );
        const objectUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = objectUrl;
        link.setAttribute('download', `${fileName}${moment().format('YYYY-MM-DD')}`);

        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(link.href);
        link.remove();
      });
    } finally {
      this.loading = false;
    }
  }

  * summary(summaryTypes) {
    this.loadingTotal = true;
    const { search: searchTmp } = toJS(this._args);
    const type = toJS(this._tabKey);
    const summaryTmp = {};
    try {
      for (const summaryType of summaryTypes) {
        const search = _.cloneDeep(searchTmp);
        search.type = summaryType;
        summaryTmp[summaryType] = yield api.totalInfo({ search }, type);
      }
      this.summaryData = summaryTmp;
    } finally {
      this.loadingTotal = false;
    }
  }

  * fetchCompaniesOptions() {
    this.loading = true;
    try {
      const res = yield api.fetchCompanyData();
      this.companyOptions = this.formatCompanyOptions(res);
    } finally {
      this.loading = false;
    }
  }

  * getCompanyDriver(companyId) {
    this.loading = true;
    try {
      const res = yield api.fetchDriverData({ companyId });
      this.driverOptions = this.formatDriverOptions(res);
    } finally {
      this.loading = false;
    }
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
    const summaryTypes = toJS(this._summaryTypes);
    this.summary(summaryTypes);
  }

  get tabKey() {
    return this._tabKey;
  }

  set tabKey(value) {
    this._tabKey = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }

  get summaryTypes() {
    return this._summaryTypes;
  }

  set summaryTypes(value) {
    this._summaryTypes = value;
    this.summary(value);
  }

  /**
   * @func 格式化承运商选择数据
   * @desc
   * @param {}
   * @return {}
   */
  formatCompanyOptions(data) {
    const res = [];
    if (data.length <= 0) return res;
    for (const item of data) {
      const { name, code } = item;
      res.push({
        label: name,
        value: code,
      });
    }
    return res;
  }

  /**
   * @func 格式化司机选择数据
   * @desc
   * @param {}
   * @return {}
   */
  formatDriverOptions(data) {
    const res = [];
    if (data.length <= 0) return res;
    for (const item of data) {
      const { username, fullname } = item;
      res.push({
        label: fullname,
        value: username,
      });
    }
    return res;
  }
}
